package com.kdzy.lshy.socity_server.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kdzy.lshy.socity_server.common.Constants;
import com.kdzy.lshy.socity_server.common.ResultMap;
import com.kdzy.lshy.socity_server.repository.BaseDao;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author rtt
 */
@Service
public class OfficerService extends BaseService {

    private static final Logger logger = LoggerFactory.getLogger(OfficerService.class);

    @Resource
    private BaseDao baseDao;

    //登录并获取所对应的权限名
    public Object officeLogin(String param, HttpServletRequest request) {

        String status = null;
        String info = null;
        Object content = null;
        try {
            if (!StringUtils.isBlank(param)) {

                JSONObject jsonObject = JSON.parseObject(param);
                String officer_number = jsonObject.getString("officer_number");
                String password = jsonObject.getString("password");
                Integer visitPlat = jsonObject.getInteger("visit_plat");//访问平台
                Integer visit_type = jsonObject.getInteger(" visit_type");//访问类型	0测试  1生产
                Integer version = jsonObject.getInteger("version ");////数据版本 0:测试 1:生产
                Integer is_used = jsonObject.getInteger("is_used");//数据是否使用：0有效 1失效
                Long stamp = jsonObject.getLong("stamp"); // 时间戳

                //办公人员登录，并获取相对应的权限名
                String sql = "select rights.name rin,role.name rn,o.* \n" +
                        "                       from role,rights,rights_role_milldle rrm,officer o,officer_role off\n" +
                        "                       where rrm.rights_id=rights.ID\n" +
                        "                       and rrm.role_id=role.ID \n" +
                        "                       and off.officer_id=o.ID\n" +
                        "                       and off.role_id=role.ID\n";

                StringBuilder sql1 = new StringBuilder(sql);
                List<Object> tags = new ArrayList<Object>();

                if (StringUtils.isNoneBlank(StringUtils.trim(officer_number))) {
                    sql1.append(" and o.officer_number= ?");
                    tags.add(officer_number);
                }
                if (StringUtils.isNoneBlank(StringUtils.trim(password))) {
                    sql1.append(" and o.password= ?");
                    tags.add(password);
                }
                if (visit_type != null) {
                    sql1.append(" AND rights.visit_type = ?");
                    tags.add(visit_type);
                    sql1.append(" AND o.visit_type = ?");
                    tags.add(visit_type);
                }
                if (version != null) {
                    sql1.append(" AND rights.version = ?");
                    tags.add(version);
                    sql1.append(" AND o.version = ?");
                    tags.add(version);
                }
                if (is_used != null) {
                    sql1.append(" AND rights.is_used = ?");
                    tags.add(is_used);
                    sql1.append(" AND o.is_used = ?");
                    tags.add(is_used);
                }
                List<Map<String, Object>> list = baseDao.queryForList(sql1.toString(), tags.toArray());
                logger.info(String.valueOf(list.size()));
                if (list.size() > 0) {
                    request.getSession().setAttribute("list", list);
                    status = Constants.http_status_success;
                    info = Constants.http_info_success;
                    content = list.get(0);//获取集合中的第一条数据

                    //*********************************判断工作人员是否可以看到居住证卡片*********************************
                    LinkedHashMap<Object, Object> map = ResultMap.creatReault(status, info, content);

                    // 判断工作人员是否可以看到居住证的办理卡片
                    String isResidentSql = "SELECT\n" +
                            "\tcount(*) AS count,\n" +
                            "\n" +
                            "IF (\n" +
                            "\t1 = 1,\n" +
                            "\t(\n" +
                            "\t\tSELECT\n" +
                            "\t\t\tb.ID\n" +
                            "\t\tFROM\n" +
                            "\t\t\tbizz b\n" +
                            "\t\tWHERE\n" +
                            "\t\t\tb.bizz_name = '居住证办理'\n" +
                            "\t),\n" +
                            "\t'0'\n" +
                            ") AS residentId,\n" +
                            "\n" +
                            "IF (\n" +
                            "\t(\n" +
                            "\t\t'"+officer_number+"' IN (\n" +
                            "\t\t\tSELECT\n" +
                            "\t\t\t\toffa.officer_number\n" +
                            "\t\t\tFROM\n" +
                            "\t\t\t\tofficer_role offr,\n" +
                            "\t\t\t\tofficer offa\n" +
                            "\t\t\tWHERE\n" +
                            "\t\t\t\toffr.role_id IN (\n" +
                            "\t\t\t\t\t'leader18f705d08db6479d8e14b8d11b'\n" +
                            "\t\t\t\t)\n" +
                            "\t\t\tAND offa.ID = offr.officer_id\n" +
                            "\t\t)\n" +
                            "\t),\n" +
                            "\t0,\n" +
                            "\t1\n" +
                            ") AS isLeader\n" +
                            "FROM\n" +
                            "\tofficer off,\n" +
                            "\tofficer_department od\n" +
                            "WHERE\n" +
                            "\toff.ID = od.officer_id\n" +
                            "AND od.dep_id = 'dep007c9042168b5594edc8fa82490a3'\n" +
                            "AND off.officer_number = '"+officer_number+"'";
                    List<Map<String, Object>> isResidentRes = baseDao.getAllByCondition(isResidentSql);
                    if (isResidentRes != null && isResidentRes.size() == 1) {
                        Long count = (Long) isResidentRes.get(0).get("count"); // 总数
                        Long isLeader = (Long) isResidentRes.get(0).get("isLeader"); // 是否是大领导
                        String residentId = (String) isResidentRes.get(0).get("residentId"); // 居住证办理业务id

                        if (count == 0) { // 不显示居住证卡片
                            if (isLeader == 0) { // 大领导
                                map.put("isResident", 0);
                                map.put("residentId", residentId);
                            } else {
                                map.put("isResident", 1);
                            }
                        }
                        if (count == 1) { // 显示居住证卡片
                            map.put("isResident", 0);
                            map.put("residentId", residentId);
                        }

                    }
                    //*********************************判断工作人员是否可以看到居住证卡片*********************************

                    //*********************************判断工作人员是否可以看到意见反馈按钮*********************************
                    if (StringUtils.equals("off001", officer_number)) { // 证明是off001工号
                        map.put("isFeedback", 0); // 表示能看到
                    } else {
                        map.put("isFeedback", 1); // 表示不能看到
                    }
                    //*********************************判断工作人员是否可以看到意见反馈按钮*********************************

                    //*********************************保存redis*********************************
                    String officerId = (String) list.get(0).get("ID"); // 工作人员id

                    // TODO 生成该用户对应的token，存入redis中
                    Jedis jedis = new Jedis("140.143.210.101", 6379);
                    jedis.auth("q1w2e3r4t5");

                    String systoken = UUID.randomUUID().toString().replace("-", ""); // 全局token

                    // 封装参数
                    Map<String, String> infoMap = new HashMap<String, String>();
                    infoMap.put("systoken", systoken);
                    infoMap.put("officerId", officerId);

                    jedis.hmset(systoken, infoMap);
                    jedis.expire(systoken, 3600); // 设置有效期为2个小时

                    map.put("systoken", systoken);

                    logger.info("出去《工作人员端 - 登录》login()方法；出参 = " + JSON.toJSONString(map));
                    jedis.close();
                    //*********************************保存redis*********************************

                    return map;
                }
                if (list.size() == 0) {
                    status = Constants.password_wrong;
                    info = "工号或密码错误，请重新登录！！";
                }

            } else {
                status = Constants.http_status_fk;//状态-9
                info = Constants.http_info_bank;
            }
        } catch (Exception e) {
            e.printStackTrace();
            status = Constants.http_status_fail;
            info = Constants.http_info_error;
        }
        return ResultMap.creatReault(status, info, content);
    }

    ;

    //办公人员登退
    public Object edit(String param, HttpServletRequest request) {

        String status = null;
        String info = null;
        Object content = null;

        JSONObject jsonObject = JSON.parseObject(param);
        String id = jsonObject.getString("officer_id");//通过工号退出
        String sql = "select * from officer where ID='" + id + "'";
        List<Map<String, Object>> list = baseDao.queryForList(sql);
        try {
            if (list.size() > 0) {
                request.getSession().removeAttribute("list");
                status = Constants.http_status_success;
                info = Constants.http_info_success;
            }
            if (list.size() == 0) {
                status = Constants.http_status_success;
                info = Constants.http_info_bank;
            }
        } catch (Exception e) {
            e.printStackTrace();
            status = Constants.http_status_success;
            info = Constants.http_info_error;
        }
        return ResultMap.creatReault(status, info, content);
    }

    //工作端办事员个人信息
    public Object officerInformation(String param) {

        String status = null;
        String info = null;
        Object content = null;

        JSONObject jsonObject = JSON.parseObject(param);
        String id = jsonObject.getString("id");
        Integer visitPlat = (Integer) jsonObject.get("visit_plat");//访问平台
        Integer visit_type = jsonObject.getInteger(" visit_type");//访问类型	0测试  1生产
        Integer version = jsonObject.getInteger("version ");////数据版本 0:测试 1:生产
        Integer is_used = jsonObject.getInteger("is_used");//数据是否使用：0有效 1失效
        Long stamp = (Long) jsonObject.getLong("stamp"); // 时间戳

//        String sql = "select o.*,r.name rn,r.descs rd,d.dep_name,ri.name rin,ri.descs rid from officer o,officer_department od,departments d,officer_role ofr,role r,rights ri,rights_role_milldle rrm" +
//                "                               where od.officer_id=o.ID and od.dep_id=d.ID and ofr.officer_id=o.ID and ofr.role_id=r.ID and rrm.rights_id=ri.ID";

        String sql = "SELECT o.* FROM officer o WHERE 1=1";

        StringBuilder sql1 = new StringBuilder(sql);
        List<Object> tags = new ArrayList<Object>();

        if (StringUtils.isNoneBlank(StringUtils.trim(id))) {
            sql1.append(" and o.ID= ?");
            tags.add(id);
        }
        if (visit_type != null) {
            sql1.append(" AND o.visit_type = ?");
            tags.add(visit_type);
        }
        if (version != null) {
            sql1.append(" AND o.version = ?");
            tags.add(version);
        }
        if (is_used != null) {
            sql1.append(" AND o.is_used = ?");
            tags.add(is_used);
        }

        List<Map<String, Object>> list = baseDao.queryForList(sql1.toString(), tags.toArray());
        try {
            if (list.size() > 0) {
                status = Constants.http_status_success;
                info = Constants.http_info_success;
                content = list.get(0);//获取集合中的第一条数据
            }
            if (list.size() == 0) {
                status = Constants.http_status_fail;
                info = Constants.http_info_bank;
            }
        } catch (Exception e) {
            e.printStackTrace();
            status = Constants.http_status_fail;
            info = Constants.http_info_error;
        }
        return ResultMap.creatReault(status, info, content);
    }
}

